﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Diagnostics;
using System.Drawing.Imaging;


namespace UFSControl
{

    public partial class ProgrammList : Form
    {
        private string vURL;
        private string vEPGURL;
        private string vSenderURL;
        private string vDetailURL;
        private string vDetailEPGURL;
        private string vAddTimerURL;
        private DateTime vTime = DateTime.Now;
        private string vUrlGoogle;
        private string vStreamUrl;
        private string vMediaPlayer;
        private Boolean vDayLightSaving;

        public ProgrammList(Point StartPoint): this()
        {
            //Position bestimmer
            this.StartPosition = FormStartPosition.Manual;
            this.Location = StartPoint;
        }
            
        public ProgrammList()
        {
            
            InitializeComponent();
            //Columns anlegen
            this.listView1.Columns.Add("1", "Icon", 48);
            this.listView1.Columns.Add("2", "Nr.", 30);
            this.listView1.Columns.Add("3", "Name", 160);
            this.listView1.Columns.Add("4", "Programm", 260);
            this.listView1.Columns.Add("5", "Zeit", 100);
            this.listView1.Columns.Add("6", "tvtvId", 0);
            this.listView1.Columns.Add("7", "startticks", 0);
            this.listView1.Columns.Add("8", "progress", 0);

            //this.listView1.Items.Add("1", "1", 0);
            //this.listView1.Items[listView1.Items.Count - 1].SubItems.Add("ORF");
            //this.listView1.Items[listView1.Items.Count - 1].SubItems.Add("Programm");

            //Icons einlesen
            ReadImages();
            //Adresse einlesen
            IniFile lIni = new IniFile();
            var lip = lIni.Read("IP", "Receiver");
            vURL = "http://" + lip + ":9000/xmlfeeds/channelTable?start-index=1&max-results=1000&channel-type=tv";
            vEPGURL = "http://" + lip + ":9000/xmlfeeds/currentEpgTable?start-index=1&max-results=1000";
            vSenderURL = "http://" + lip + ":9000/cmds/changeChannel?channel-no=";
            vDetailURL = "http://" + lip + ":9000/xmlfeeds/detailedInfo?start-index=";
            vDetailEPGURL = "http://" + lip + ":9000";
            //vAddTimerURL = "http://" + lip + ":9000/cmds/setTimer?channel-no=";
            vAddTimerURL = "http://" + lip + ":9000/cmds/setExternalTimer?channel-type=tv&channel-no=";
            vUrlGoogle = lIni.Read("URL", "Webbroser");
            vStreamUrl = "http://" + lip + ":49152/content/live-streaming/liveStream-http-channelNumber-1.ts";
            vMediaPlayer = lIni.Read("EXE", "Mediaplayer");
            vDayLightSaving = TimeZoneInfo.Local.IsDaylightSavingTime(DateTime.Now);

            timeBox.Text = String.Format("{0:00}:{1:00}", vTime.Hour, vTime.Minute);
            //Update Timer aktiv schalten
            updateTimer.Enabled = true;
            //Refresh Timer scharf machen
            Int16 intervall;
            try
            {
                intervall = Convert.ToInt16(lIni.Read("INTERVALL", "Receiver"));
            }
            catch
            {
                intervall = 0;
            }
            if (intervall > 0)
            {
                refreshTimer.Enabled = true;
                refreshTimer.Interval = intervall * 60000;
            }

            //Kanalliste erstellen
            this.GenerateEPGList(0);
        }

        //an eine WEbadresse einen REquest schicken und das Ergebnis als String zurückliefern
        private string SendWebRequest(Uri aURL)
        {
            string lresponseFromServer = "";

            WebRequest lRequest = WebRequest.Create(aURL);
            ((HttpWebRequest)lRequest).UserAgent = "Eigenbau";
            lRequest.Method = "GET";
            lRequest.ContentType = "text/html";
            //Stream ldataStream = lrequest.GetRequestStream();
            // Set the 'Timeout' property in Milliseconds.
            lRequest.Timeout = 30000;
            try
            {
                // Get the response.
                WebResponse lResponse = lRequest.GetResponse();

                // Get the stream containing content returned by the server.
                Stream ldataStream = lResponse.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader lreader = new StreamReader(ldataStream);
                // Read the content.
                lresponseFromServer = lreader.ReadToEnd();

                // Clean up the streams.
                lreader.Close();
                ldataStream.Close();
                lResponse.Close();
                return lresponseFromServer;
            }
            catch
            {
                //Timeout abfangen
                MessageBox.Show("Request timed out");
                return ""; //Programm verlassen

            }
        }

        private string PrintDayOfWeek(DayOfWeek day)
        {
            switch (day){
                case DayOfWeek.Monday: 
                    return "Mo";
                case DayOfWeek.Tuesday:
                    return "Di";
                case DayOfWeek.Wednesday:
                    return "Mi";
                case DayOfWeek.Thursday:
                    return "Do";
                case DayOfWeek.Friday:
                    return "Fr";
                case DayOfWeek.Saturday:
                    return "Sa";
                case DayOfWeek.Sunday:
                    return "So";
            }
            return "  ";

        }

        private void GenerateChannelTable()
        {
            Uri lUri = new Uri(vURL);
            string lresponseFromServer = SendWebRequest(lUri);
            
            //XML Elemente durchgehen
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(lresponseFromServer);
            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("./channel");
            try
            {
                string channelNr;
                string channelName;
                string tvtId;
                string channelIcon = "";
                foreach (XmlNode i in nodes)
                {
                    channelNr = i["channelNumber"].InnerText;
                    channelName = i["channelName"].InnerText;
                    tvtId = i["tvtvId"].InnerText;
                    if (i["channelIcon"] != null) { channelIcon = i["channelIcon"].InnerText; } else { channelIcon = ""; }
                    listView1.Items.Add(new ListViewItem(new string[] { channelNr, "", channelName, channelIcon, tvtId })); 
                                                                        

                }
            }
            catch
            {
            }
        }

        private void ReadImages()
        {
            channelImageList.Images.Clear();
            string[] bilder = System.IO.Directory.GetFiles(Application.StartupPath + "\\resources\\", "*.jpg");
            foreach (string item in bilder)
            {
                Image bild = new Bitmap(item);
                string key = item;
                key = key.Replace(Application.StartupPath + "\\resources\\", "");
                key = key.Replace(".jpg", "");
                channelImageList.Images.Add(key, bild);
            } 

        }

        private void GenerateEPGList(Int64 ltime)
        {
            string lresponseFromServer = "";
            string lTimeOffset = "";
            ProgressForm lProgress = new ProgressForm();
            lProgress.StartPosition = FormStartPosition.CenterParent;
            lProgress.Show(this);
            lProgress.SetProgress("Lade Daten", 0);
            if (ltime != 0)
            {
                lTimeOffset = "&start-time=" + Convert.ToString(ltime);
            }
            Uri lUri = new Uri(vEPGURL + lTimeOffset);

            //Daten anfordern
            lresponseFromServer = SendWebRequest(lUri);
            //wenn keine Daten gefunden, dann exit
            if (lresponseFromServer == "") {return;}
            lProgress.SetProgress("Erzeuge Liste", 50);
            //XML Elemente durchgehen
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(lresponseFromServer);
            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("./channel");
            //Liste leeren, sie könnte ja schon mal befüllt worden sein
            listView1.Items.Clear();
            try
            {
                string channelNr;
                string channelName;
                string tvtId;
                string channelIcon = "";
                string programm = "";
                string zeit = "";
                string startTime = "";
                string progress = "";
                //float zeitPzt = 0;
                DateTime UnixEpoch;
                foreach (XmlNode i in nodes)
                {
                    channelNr = i["channelNumber"].InnerText;
                    channelName = i["channelName"].InnerText;
                    if (i["progress"] != null){progress = i["progress"].InnerText;}else {progress = "";}
                    tvtId = i["tvtvId"].InnerText;
                    if (i["channelIcon"] != null) { 
                        channelIcon = i["channelIcon"].InnerText;
                        channelIcon = channelIcon.Replace("/tvtv/", "");
                    } else { 
                        channelIcon = ""; 
                    }
                    if (i["title"] != null) { programm = i["title"].InnerText; } else { programm = ""; }
                    if (i["startTime"] != null) {
                        startTime = i["startTime"].InnerText;
                        UnixEpoch = new DateTime(Convert.ToInt64(i["startTime"].InnerText) * 10000000); //Ticks
                        UnixEpoch = UnixEpoch.AddYears(1969);
                        // je nach Sommer oder Winterzeit muss die Uhrzeit korrigiert werden
                        // Ticks uns UnixEpoch sind mindesten 1h unterschiedlich
                        if (vDayLightSaving) { UnixEpoch = UnixEpoch.AddHours(2); } else { UnixEpoch = UnixEpoch.AddHours(1); }
                        zeit = String.Format("{0} {1:00}:{2:00}", PrintDayOfWeek(UnixEpoch.DayOfWeek), UnixEpoch.Hour, UnixEpoch.Minute);
                    } else { 
                        zeit = "";
                        startTime = "";
                    }
                    if (i["endTime"] != null) {
                        UnixEpoch = new DateTime(Convert.ToInt64(i["endTime"].InnerText) * 10000000); //Ticks +1h offset
                        if (vDayLightSaving) { UnixEpoch = UnixEpoch.AddHours(2); } else { UnixEpoch = UnixEpoch.AddHours(1); }
                        zeit += " - " + String.Format("{0:00}:{1:00}", UnixEpoch.Hour, UnixEpoch.Minute); 
                    }
                    ListViewItem listItem = listView1.Items.Add(new ListViewItem(new string[] { "", channelNr, channelName, programm, zeit, tvtId, startTime, progress }));
                    if (channelIcon != "")
                    {
                        //Icon aus der Liste suchen
                        (listItem).ImageIndex = channelImageList.Images.IndexOfKey(channelIcon);

                    }
                    else
                    {
                        (listItem).ImageIndex = channelImageList.Images.IndexOfKey("0"); 
                    }

                }
            }
            catch
            {
            }
            lProgress.SetProgress("Fertig ...", 100);
            lProgress.Close();
        }

        private void ChangeChannelClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                return;
            }

            //zu Sender in der Liste wechseln
            string channelNr = listView1.SelectedItems[0].SubItems[1].Text;
            Uri lUri = new Uri(vSenderURL + channelNr);
            SendWebRequest(lUri);
        }

        private void OnSelectedIndexChange(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                return;
            }
            //zu Sender detail Info anzeigen
            string channelNr = listView1.SelectedItems[0].SubItems[1].Text;
            Uri lUri = new Uri(vDetailURL + channelNr + "&start-time=" + listView1.SelectedItems[0].SubItems[6].Text);
            
            string lresponseFromServer = SendWebRequest(lUri); ;
            //XML Elemente durchgehen
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(lresponseFromServer);
            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("./event");
            try
            {
                string longInfo;
                string zeit = "";
                DateTime UnixEpoch;
                richTextBox.Text = ""; //Text leer setzen, vielleicht ist ja kein Dokument geschickt worden
                foreach (XmlNode i in nodes)
                {
                    if (i["longInfo"] != null) { 
                        longInfo = i["longInfo"].InnerText;
                        longInfo = longInfo.Replace("<br>", "\n");
                    } else {
                        longInfo = ""; 
                    }
                    if (i["startTime"] != null)
                    {
                        UnixEpoch = new DateTime(Convert.ToInt64(i["startTime"].InnerText) * 10000000); //Ticks
                        if (vDayLightSaving) { UnixEpoch = UnixEpoch.AddHours(2); } else { UnixEpoch = UnixEpoch.AddHours(1); }// Time Offset
                        zeit = String.Format("{0:00}:{1:00}", UnixEpoch.Hour, UnixEpoch.Minute);
                    }
                    else { zeit = ""; }
                    if (i["endTime"] != null)
                    {
                        UnixEpoch = new DateTime(Convert.ToInt64(i["endTime"].InnerText) * 10000000); //Ticks +1h offset
                        if (vDayLightSaving) { UnixEpoch = UnixEpoch.AddHours(2); } else { UnixEpoch = UnixEpoch.AddHours(1); }// Time Offset
                        zeit += " - " + String.Format("{0:00}:{1:00}", UnixEpoch.Hour, UnixEpoch.Minute);
                    }
                    richTextBox.Text = zeit + "\n" + longInfo;


                }
            }
            catch
            {
            }
        }

        private void OnEPGClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                return;
            }
            //zu Sender EPG Info anzeigen
            string channelNr = listView1.SelectedItems[0].SubItems[1].Text;
            string tvtId = listView1.SelectedItems[0].SubItems[5].Text;
            string channelName = listView1.SelectedItems[0].SubItems[2].Text; 
            EPGDetail lEpgForm = new EPGDetail(vDetailEPGURL, channelNr, tvtId, channelName);
            lEpgForm.ShowDialog();
        }

        private void OnAddTimer(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                return;
            }
            //Timer hinzufügen
            string channelNr = listView1.SelectedItems[0].SubItems[1].Text;
            Uri lUri = new Uri(vAddTimerURL + channelNr + 
                               "&start-time=" + listView1.SelectedItems[0].SubItems[6].Text + 
                               "&end-time=" + Convert.ToString(Convert.ToInt64(listView1.SelectedItems[0].SubItems[6].Text) + 6000));
                               //"&tvtv-Id=" + listView1.SelectedItems[0].SubItems[5].Text);

            string lresponseFromServer = SendWebRequest(lUri); ;
        }

        private void OnUpButtonClick(object sender, EventArgs e)
        {
            vTime = vTime.AddMinutes(15);
            timeBox.Text = String.Format("{0:00}:{1:00}", vTime.Hour, vTime.Minute);  
        }

        private void OnDownButtonClick(object sender, EventArgs e)
        {
            vTime = vTime.AddMinutes(-15);
            timeBox.Text = String.Format("{0:00}:{1:00}", vTime.Hour, vTime.Minute);
        }

        private void OnSearchButtonClick(object sender, EventArgs e)
        {
            DateTime lUFSTime;
            Int64 lTicks;

            lUFSTime = vTime.AddYears(-1969);
            if (vDayLightSaving) { lUFSTime = lUFSTime.AddHours(-2); } else { lUFSTime = lUFSTime.AddHours(-1); }// Time Offset
            lTicks = lUFSTime.Ticks / 10000000;
            this.GenerateEPGList(lTicks);
        }

        private void OnKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {
                e.Handled = true;
                //Eingabe berechnen
                OnLeave(sender, e);
                searchButton.Focus(); //Focus auf den Suchbutton legen
            }
        }

        private void OnLeave(object sender, EventArgs e)
        {
            //Eingabe berechnen
            //Stunde und Minuten aufsplitten
            string[] splittedString = timeBox.Text.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
            if (splittedString.Length < 2)
            {
                //falsche  Eingabe, Wert zurücksetzen
                timeBox.Text = String.Format("{0:00}:{1:00}", vTime.Hour, vTime.Minute);
                return;
            }
            try
            {

                string lStunden = splittedString[0];
                string lMinuten = splittedString[1];
                vTime.AddHours(Convert.ToInt16(splittedString[0]) - vTime.Hour + 1);
                vTime.AddMinutes(Convert.ToInt16(splittedString[1]) - vTime.Minute);
            }
            catch
            {
                //Exception still fangen
            }
        }

        private void OnGoogleClick(object sender, EventArgs e)
        {
            string title = listView1.SelectedItems[0].SubItems[3].Text;
            if (title.IndexOf("(") > 0)
            {
                int pos = title.IndexOf("(");
                int len = title.LastIndexOf(")") - pos + 1;
                if (len <= 0) { len = int.MaxValue; } 
                title = title.Remove(pos, len);
            }
            title = title.Trim();
            title = title.Replace(" ", "+"); //Leerzeichen werden in + umgewandelt
            Process.Start(vUrlGoogle + title);
        }

        private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
        {
            //Hintergrund zeichen
            Color lFarbe = Color.Silver;
            Rectangle rect = new Rectangle(e.Bounds.Left + 1, e.Bounds.Top + 1, e.Bounds.Width - 2, e.Bounds.Height - 2);
            SolidBrush lbr = new SolidBrush(lFarbe);
            e.Graphics.FillRectangle(lbr, rect);
            //Text ausgeben
            StringFormat string_format = new StringFormat();
            string_format.Alignment = StringAlignment.Center;
            string_format.LineAlignment = StringAlignment.Center;
            e.Graphics.DrawString(listView1.Columns[e.ColumnIndex].Text, listView1.Font, Brushes.Black, e.Bounds);
        }

        private void DrawBackGround(DrawListViewSubItemEventArgs e)
        {
            //Rectangle rect = new Rectangle(e.Bounds.Left + 1, e.Bounds.Top + 1, e.Bounds.Width - 2, e.Bounds.Height - 2);
            Rectangle rect = new Rectangle(e.Bounds.Left, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height);
            SolidBrush lbr = new SolidBrush(Color.Blue);
            e.Graphics.FillRectangle(lbr, rect);
        }

        private void DrawCell(string Text, Boolean selected, DrawListViewSubItemEventArgs e)
        {
            //Ausgabeformat
            StringFormat string_format = new StringFormat();
            string_format.Trimming = StringTrimming.EllipsisWord;
            string_format.FormatFlags |= StringFormatFlags.NoWrap;
            string_format.LineAlignment = StringAlignment.Center;
            if (selected)
            {
                DrawBackGround(e);
                e.Graphics.DrawString(Text, e.Item.ListView.Font, Brushes.White, e.Bounds, string_format);
            }
            else
            {
                e.Graphics.DrawString(Text, e.Item.ListView.Font, Brushes.Black, e.Bounds, string_format);
            }
        }

        private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
        {
            // Get the ListView item and the ServerStatus object.    
            ListViewItem item = e.Item;
            ListView lvw = e.Item.ListView;
            Image logo = null;
            //Ausgabeformat
            //StringFormat string_format = new StringFormat();
            //string_format.Trimming = StringTrimming.EllipsisWord;
            //string_format.FormatFlags |= StringFormatFlags.NoWrap;
            //string_format.LineAlignment = StringAlignment.Center;
            //Zeichen Font
            //Font  myFont = new Font(lvw.Font, FontStyle.Regular);
            Boolean selected = !((e.ItemState & ListViewItemStates.Selected) == 0);
            if ((item).ImageIndex >= 0)
            {
                logo = channelImageList.Images[(item).ImageIndex];
            }
            // Draw.    
            switch (e.ColumnIndex)
            {        
                case 0:
                    ImageAttributes imageAttributes = new ImageAttributes();
                    float[][] colorMatrixElements = { 
                       new float[] {1,  0,  0,  0, 0},        // red scaling factor of 2
                       new float[] {0,  1,  0,  0, 0},        // green scaling factor of 1
                       new float[] {0,  0,  2,  0, 0},        // blue scaling factor of 1
                       new float[] {0,  0,  0,  1, 0},        // alpha scaling factor of 1
                       new float[] {.2f, .2f, .2f, 0, 1}};    // three translations of 0.2

                    ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
                    imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                    // Draw logo.            
                    if (logo != null)
                    {
                        float scale = e.Bounds.Height / (float)logo.Height;
                        e.Graphics.ScaleTransform(scale, scale);
                        e.Graphics.TranslateTransform(e.Bounds.Left, e.Bounds.Top + (e.Bounds.Height - logo.Height * scale) / 2, System.Drawing.Drawing2D.MatrixOrder.Append);
                        if (selected)
                        {
                            //e.Graphics.DrawImage(logo, 0, 0);
                            //e.Graphics.DrawImage(logo, new Rectangle(0, 0, logo.Width, logo.Height), 0, 0, logo.Width, logo.Height, GraphicsUnit.Pixel, imageAttributes);
                            Bitmap logo2 = (Bitmap)logo.Clone();
                            Color c;
                            for (int i = 0; i < logo2.Width; i++)
                            {
                                for (int j = 0; j < logo2.Height; j++)
                                {
                                    c = logo2.GetPixel(i, j);
                                    logo2.SetPixel(i, j, Color.FromArgb(255 - c.R, 255 - c.G, 255 - c.B));
                                }
                            }
                            //Hintergrund blau zeichnen
                            //DrawBackGround(e);
                            //invertiertes Logo zeichnen
                            e.Graphics.DrawImage(logo2, 0, 0);
                        }
                        else
                        {
                            e.Graphics.DrawImage(logo, 0, 0);
                        }
                    }
                    break;        
                case 1:            
                    // Draw the Channel Nr. 
                    DrawCell(item.SubItems[1].Text, selected, e);
                    break;        
                case 2:            
                    // Draw the Channel Name 
                    DrawCell(item.SubItems[2].Text, selected, e);
                    break;  
                case 3:
                    // Draw Programm Name  
                    DrawCell(item.SubItems[3].Text, selected, e);
                    break;
                case 4:
                    // Draw Start/End Time
                    int lProz = 0;
                    if (item.SubItems[7].Text != "")
                    {
                        lProz = Convert.ToInt16(item.SubItems[7].Text);
                    }

                    if (lProz > 0){     
                        Color lFarbe = Color.Gray;
                        Rectangle rect = new Rectangle(e.Bounds.Left + 1, e.Bounds.Top + 1, e.Bounds.Width - 2, e.Bounds.Height - 3);
                        SolidBrush lbr = new SolidBrush(lFarbe);
                        //Rahmen zeichen
                        Pen lPen = new Pen(lFarbe);
                        e.Graphics.DrawRectangle(lPen, rect);
                        //Füllung berechnen und zeichen
                        int width = (e.Bounds.Width - 2) * lProz / 100;
                        Rectangle rectProz = new Rectangle(e.Bounds.Left + 1, e.Bounds.Top + 1, width, e.Bounds.Height - 3);
                        e.Graphics.FillRectangle(lbr, rectProz);
                    }
                    //Text ausgeben
                    //Color pen_color = Color.FromArgb(255, 255 - lFarbe.R, 255 - lFarbe.G, 255 - lFarbe.B);
                    Color pen_color = Color.Black;
                    using (SolidBrush br = new SolidBrush(pen_color))
                    {
                        StringFormat string_center = new StringFormat();
                        string_center.Alignment = StringAlignment.Center;
                        string_center.LineAlignment = StringAlignment.Center;
                        e.Graphics.DrawString(item.SubItems[4].Text, lvw.Font, br, e.Bounds, string_center); 
                    }
                    break;

            }    
            // Draw the focus rectangle if appropriate.   
            e.Graphics.ResetTransform();    
            if (lvw.FullRowSelect)  
            {        
                e.DrawFocusRectangle(e.Item.Bounds);   
            }   
        }

        private void streamAnsehenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string stream = vStreamUrl;
            string channel= listView1.SelectedItems[0].SubItems[1].Text;
            stream = stream.Replace("channelNumber", channel); //KanalNr in URL einfügen
            try
            {
                Process.Start(vMediaPlayer, stream);
            }
            // Most specific:
            catch (Win32Exception ex)
            {
                MessageBox.Show("Streaming Client konnte nicht gefunden werden: " + ex.Message);
            }
            // Least specific:
            catch (Exception ex)
            {
                MessageBox.Show("Fehler beim öffnen des Streaming Clients: " + ex.Message);
            }
        }

        private void tvInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0){return;}
            string lKanal = listView1.SelectedItems[0].SubItems[2].Text;
            IniFile lIni = new IniFile();
            var lChannel = lIni.Read(lKanal, "TVINFO");
            var lUrl = lIni.Read("TVINFO", "Webbroser");
            //Rückfallsebene, falls in der Ini nichts gefunden wird
            if (lChannel == "") lChannel = lKanal;
            Process.Start(lUrl + lChannel);
        }

        //Timer auslösen
        private void refreshTimer_Tick(object sender, EventArgs e)
        {
            //sichern der aktuellen Position
            Int32 lIndex = -1;
            if (listView1.SelectedItems.Count > 0)
            {
                lIndex = listView1.SelectedItems[0].Index;
            }
            vTime = DateTime.Now;
            timeBox.Text = String.Format("{0:00}:{1:00}", vTime.Hour, vTime.Minute);
            this.GenerateEPGList(0);
            //setzen der neuen Position nach dem Reload
            if (lIndex != -1){
                this.listView1.Items[lIndex].Focused = true;
                this.listView1.Items[lIndex].Selected = true;
            }
        }

        //Timer um die Zeit in der Combobox immer akutell zu halten
        private void updateTimer_Tick(object sender, EventArgs e)
        {
            vTime = DateTime.Now;
            timeBox.Text = String.Format("{0:00}:{1:00}", vTime.Hour, vTime.Minute);
        }

    }
}
